import 'dart:math';

import 'package:flutter/material.dart';

class HcColorUtil {
  const HcColorUtil._();

  ///判断一个颜色是否是亮色 用来判断反色
  ///[color]需要判断的颜色
  ///[limit] 变色的 界限 0-1之间
  ///[bgColor] 当前的背景颜色
  ///纯白色是255 黑色是0
  static bool needLightColor(Color color,
      {double limit = 0.75, Color? bgColor}) {
    limit = min(max(0, limit), 1);

    color = changeRGBA2GRB(color, bgColor: bgColor);
    double darkness =
        (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue);
    return darkness < 255 * limit;
  }

  static Color hex2Color(String color) {
    if (color.startsWith('#') && color.length == 7) {
// rrggbb 获取到RRGGBB转成16进制 然后在加上FF的透明度
      return Color(int.parse(color.substring(1, 7), radix: 16) + 0xFF000000);
    }
    if (color.length == 6) {}
    return Colors.white;
  }

  /// 将rgba转换成rgb颜色判断
  /// [color] 前景色
  /// [bgColor] 背景色 默认为白色
  static Color changeRGBA2GRB(Color color, {Color? bgColor}) {
    double opacity = 1 - color.opacity;
    bgColor ??= Colors.white;
    return Color.fromRGBO(
        (color.red * color.opacity + bgColor.red * opacity).round(),
        (color.green * color.opacity + bgColor.green * opacity).round(),
        (color.blue * color.opacity + bgColor.blue * opacity).round(),
        1.0);
  }

  /// 混合颜色算法
  /// [mainColor] 第一个颜色 默认白色
  /// [secondaryColor] 第二个颜色 需要传入
  /// [potency]混合颜色第一个颜色比例
  /// [opacity] 透明度在0.0-1.0之间 超出部分为1
  static Color mixColor({
    Color mainColor = Colors.white,
    required Color secondaryColor,
    double potency = 0.5,
    double opacity = 1,
  }) {
//主颜色混合比例越界判断
    potency = potency > 1 || potency < 0 ? 0.5 : potency;
//透明度越界判断
    opacity = opacity > 1 || opacity < 0 ? 1 : opacity;
//结果红色值
    int r = mainColor.red;
//结果绿色值
    int g = mainColor.green;
//结果蓝色值
    int b = mainColor.blue;
    r = (r - (r - secondaryColor.red) * (1 - potency)).round();
    g = (g - (g - secondaryColor.green) * (1 - potency)).round();
    b = (b - (b - secondaryColor.blue) * (1 - potency)).round();
    return Color.fromRGBO(r, g, b, opacity);
  }

  ///创建Material风格的color
  static MaterialColor createMaterialColor(Color color) {
    List strengths = <double>[.05];
    Map swatch = <int, Color>{};
    final int r = color.red, g = color.green, b = color.blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] = Color.fromRGBO(
        r + ((ds < 0 ? r : (255 - r)) * ds).round(),
        g + ((ds < 0 ? g : (255 - g)) * ds).round(),
        b + ((ds < 0 ? b : (255 - b)) * ds).round(),
        1,
      );
    }
    return MaterialColor(color.value, swatch as Map<int, Color>);
  }
}
